<?php

namespace app\api\controller\v2;

use api\channel\meituan\alliance\Seckill;
use app\common\service\MeituanPubJutuike;
use app\middleware\MeituanCityNameToCityId;
use think\Request;
use think\facade\Db;
use app\common\service\MeituanPub;

/**
 * 美团分销联盟吃喝玩乐
 * https://pub.meituan.com/#/api-doc
 *
 * 需要添加渠道IP地址才能调佣接口
 * 路径：美团分销联盟 -> API接口文档 -> 渠道IP地址管理，把服务器的IP加进去
 */
class Dianping extends \app\BaseController
{
    /**
     * @var MeituanPub|MeituanPubJutuike $service
     */
    protected $service;

    protected $middleware = [
        \app\middleware\ApiChannel::class => ['except' => ['provinceAll', 'provinceCities', 'cityAll']],
        \app\middleware\ApiUserAuthV2::class => ['except' => ['provinceAll', 'provinceCities', 'cityAll']],
    ];

    protected function initialize()
    {
        $this->request->servType = PRODUCT_METUAN_SERV;
        $this->request->servName = '美团到店';
        parent::initialize();
    }

    /**
     * 省份列表
     * GET
     */
    public function provinceAll()
    {
        $list = Db::name('meituan_city')
            ->field('province_id as code, name')
            ->where('city_id', 0)
            ->select()
            ->toArray();
        return success('操作成功', $list);
    }

    /**
     * 某一省份下的城市列表
     * POST
     */
    public function provinceCities()
    {
        $provinceId = input('post.province_id', 0);
        if (empty($provinceId)) {
            return fail('省份 id 不能为空');
        }

        $list = Db::name('meituan_city')
            ->field('city_id as code, name')
            ->where('province_id', $provinceId)
            ->where('city_id', '>', 0)
            ->select()
            ->toArray();
        return success('操作成功', $list);
    }

    /**
     * 获取所有省份及城市
     */
    public function cityAll()
    {
        $list = Db::name('meituan_city')
            ->field('province_id, city_id, name')
            ->order('province_id asc, city_id asc')
            ->select()
            ->toArray();
        $res = [];
        foreach ($list as $k => $v) {
            if ($v['city_id']) {
                $res[$v['province_id']]['children'][] = [
                    'code' => $v['city_id'],
                    'name' => $v['name'],
                ];
            } else {
                $res[$v['province_id']]['code'] = $v['province_id'];
                $res[$v['province_id']]['name'] = $v['name'];
            }
        }
        unset($list);
        return success('操作成功', array_values($res));
    }

    /**
     * 获取某个城市类目信息
     */
    public function cityCategories(Request $request)
    {
        $cityId = input('post.city_id', 0);
        $cityName = input('post.city_name', '');
        $cat0Id = input('post.cat0_id', 0);
        if (empty($cityId)) {
            if ($cityName) {
                $cityId = (new Seckill())->getCityIdByCityName($cityName);
            }
            if (empty($cityId)) {
                $cityId = MeituanCityNameToCityId::MEITUAN_DDEFAULT_CITYID;
            }
        }

        // 缓存
        $cacheKey = 'meituan_city_categories_' . $cityId . '_' . $cat0Id;
        $val = cache($cacheKey);
        if ($val) {
            return success('操作成功', $val);
        }

        try {
            $service = $this->getService();
        } catch (\Exception $e) {
            return fail($e->getMessage());
        }

        $res = $service->cityCategories($cityId, $cat0Id);

        if (isset($res['code']) && in_array($res['code'],[1,200])) {

            if ($service instanceof MeituanPubJutuike){
                cache($cacheKey, $res['data'], 3600 * 24);
                return success('操作成功', $res['data']);
            }else{
                cache($cacheKey,$res['msg'], 3600 * 24);
                return success('操作成功', $res['msg']);
            }
        }

        return  fail($res['msg']);




    }

    /**
     * 团单查询接口
     *
     * @param   $cat0_id    一级类目id，必须
     * @param   $geo        位置信息，必须
     * @param   $cat1_id    二级类目id，非必须
     * @param   $shop_id    商户id，非必须
     * @param   $sort_type  排序， 非必须
     * @param   $keyword    搜索关键词，非必须
     * @param   $page       页数，默认1，非必须
     * @param   $size       每页结果数，默认10，非必须
     */
    public function searchDeals(Request $request)
    {
        $params = input('post.');
        if (empty($params['cat0_id'])) {
            return fail('一级类目 id 不能为空');
        }
        if (empty($params['geo'])) {
            return fail('地理位置信息不能为空');
        }
        $geo = $params['geo'] ?? [];
        if (empty($geo['city_id']) && empty($geo['city_name'])) {
            if (empty($geo['lng']) && empty($geo['lat'])) {
                return fail('您未开启定位权限');
            }
            if (empty($geo['radii'])) {
                return fail('半径不能为空');
            }
            $geo = [
                'lng' => $geo['lng'],
                'lat' => $geo['lat'],
                'radii' => $geo['radii'],
            ];
        } elseif (!empty($geo['city_name'])) {
            $geo['city_name'] = str_replace('市', '', $geo['city_name']);
            $cityId = (new Seckill())->getCityIdByCityName($geo['city_name']);
            $geo = [
                'cityId' => $cityId,
            ];
        } else {
            $geo = [
                'cityId' => $geo['city_id'],
            ];
        }
        $params['geo'] = $geo;
        unset($geo);

        $service = $this->getService();
        $params['user_id'] = $request->user['id'];
        $params['agent_id'] = $request->agentChannel['agent_id'];
        $params['channel_id'] = $request->agentChannel['id'];
        $res = $service->searchDeals($params);
        if (!isset($res['code']) || !in_array($res['code'],[1,200])) {
            return fail('获取失败：' . ($res['msg'] ?? ''));
        }

        if ($service instanceof MeituanPubJutuike){
            return success('操作成功', $res['data']);
        }else{
            return success('操作成功', $res['msg']);
        }

    }

    /**
     * 订单列表
     */
    /**
     * 订单列表
     */
    public function orderList(Request $request)
    {
        $where[] = ['agent_id', '=', $request->agentChannel['agent_id']];
        $where[] = ['user_id', '=', $request->user['id']];
        $where[] = ['order_type', '=', TAKEOUT_ORDER_MEITUAN_PUB];

        $params = input('post.');
        if (!empty($params['status'])) {
            $where[] = ['status', '=', $params['status']];
        }

        $list = Db::name('takeout_order')
            ->field('order_type, order_id, paytime, payprice, title, status, img')
            ->where($where)
            ->order('id desc')
            ->paginate([
                'page' => $params['page'] ?? 1,
                'list_rows' => $params['list_rows'] ?? 10,
            ])->toArray();
        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['payprice'] = fen2yuan($v['payprice']);
        }

        return success('操作成功', $list);
    }

    /**
     * initialize 方法在中间件之前执行，如果放在初始化中则会报错
     */
    protected function getService(){
        if (env('MEITUAN_IS_JUTUIKE')){
            return $this->service = new MeituanPubJutuike(\app\common\facade\auth\Auth::agentId());
        }else{
            return $this->service = new MeituanPub(\app\common\facade\auth\Auth::agentId());
        }

    }
}
